# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys,time

from piHAparsers import (Decoders,Parsers)
from piHAlibs import (debug,log2console,log2file,printer,raw2netq)
from .controller import CONTROLLER
from .corelibs import (sysevents)
from .coresetup import (SetupDaemons)
from .netcontroller import NETCONTROLLER

logger = logging.getLogger()

posttargets = [printer(),]


def useparser(ctrl,dev):
    for decoder in Decoders[ctrl]:
        dev.decoders.append(decoder(posttargets))
    dev.featurenames.append(ctrl + '-PARSER')
    dev.features.append(Parsers[ctrl](dev.decoders))


def usecontroller(ctrl,port):
    try:
        dev = CONTROLLER(ctrl,port)
    except Exception as e:
        logger.error("%s : %s", repr(e.__class__), str(e))
        return None
    dev.name = ctrl
    dev.tsetup()
    if not dev.setup: return None
    dev.allrxtx()
    SetupDaemons.setdefault(ctrl)
    SetupDaemons[ctrl] = dev
    if 'TCPRX' in SetupDaemons:
        dev.featurenames.append('RAW2NETQ')
        dev.features.append(raw2netq(SetupDaemons['TCPRX'].evtnetq))
    return dev


def usenetcontroller(nctrl,hostport):
    try:
        dev = NETCONTROLLER(nctrl,hostport)
    except Exception as e:
        logger.error("%s : %s", repr(e.__class__), str(e))
        return None
    dev.name = nctrl
    dev.tsetup()
    if not dev.setup: return None
    dev.allrxtx()
    SetupDaemons.setdefault(nctrl)
    SetupDaemons[nctrl] = dev
    return dev
